<template>
  <div class="withdraw">
    <div class="page-header">
      <h2 class="page-title">提现</h2>
      <p class="page-subtitle">将 USDT 提现到外部地址</p>
    </div>
    
    <el-card class="withdraw-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Download /></el-icon>
          <span>提现</span>
        </div>
      </template>
      
      <el-alert
        title="提现说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <p>1. 提现需要支付网络手续费</p>
        <p>2. 提现到账时间取决于网络确认速度</p>
        <p>3. 请确保提现地址正确，错误地址可能导致资产丢失</p>
      </el-alert>
      
      <el-form
        ref="withdrawFormRef"
        :model="withdrawForm"
        :rules="withdrawRules"
        label-width="120px"
      >
        <el-form-item label="提现地址" prop="to">
          <el-input
            v-model="withdrawForm.to"
            placeholder="请输入提现地址"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="0.0001"
            :precision="4"
            :step="0.0001"
            style="width: 100%"
          />
          <div class="form-tip">
            当前余额: {{ formatBalance(balance) }} USDT
            <br>
            预计手续费: {{ formatBalance(fee) }} USDT
            <br>
            实际到账: {{ formatBalance(actualAmount) }} USDT
          </div>
        </el-form-item>
        
        <el-form-item label="币种">
          <el-select v-model="withdrawForm.currency" style="width: 100%">
            <el-option label="USDT" value="USDT" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注（可选）" prop="memo">
          <el-input
            v-model="withdrawForm.memo"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleWithdraw"
          >
            确认提现
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { walletApi } from '../api/wallet'

const withdrawFormRef = ref<FormInstance>()
const loading = ref(false)
const balance = ref(0)
const fee = ref(0.001) // 默认手续费

const withdrawForm = reactive({
  to: '',
  amount: 0,
  currency: 'USDT',
  memo: ''
})

const actualAmount = computed(() => {
  return Math.max(0, withdrawForm.amount - fee.value)
})

const withdrawRules = {
  to: [
    { required: true, message: '请输入提现地址', trigger: 'blur' },
    { min: 26, max: 42, message: '地址长度不正确', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 0.0001, message: '金额不能少于0.0001', trigger: 'blur' }
  ]
}

onMounted(async () => {
  await loadBalance()
})

const loadBalance = async () => {
  try {
    const balanceData = await walletApi.getBalance()
    balance.value = balanceData.total || 0
  } catch (error) {
    console.error('加载余额失败:', error)
  }
}

const handleWithdraw = async () => {
  if (!withdrawFormRef.value) return
  
  await withdrawFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (withdrawForm.amount + fee.value > balance.value) {
      ElMessage.error('余额不足（包含手续费）')
      return
    }
    
    try {
      await ElMessageBox.confirm(
        `确认提现 ${withdrawForm.amount} ${withdrawForm.currency} 到地址 ${withdrawForm.to}?`,
        '确认提现',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      loading.value = true
      const result = await walletApi.withdraw({
        to: withdrawForm.to,
        amount: withdrawForm.amount,
        currency: withdrawForm.currency,
        memo: withdrawForm.memo
      })
      
      ElMessage.success('提现申请已提交，请等待处理')
      resetForm()
      await loadBalance()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '提现失败')
      }
    } finally {
      loading.value = false
    }
  })
}

const resetForm = () => {
  if (withdrawFormRef.value) {
    withdrawFormRef.value.resetFields()
  }
  withdrawForm.to = ''
  withdrawForm.amount = 0
  withdrawForm.memo = ''
}

const formatBalance = (value: number) => {
  return value.toFixed(4)
}
</script>

<style scoped>
.withdraw {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.withdraw-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.5;
}
</style>

